<!DOCTYPE HTML>
<html lang="zh-Hans">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Java多线程面试题, java">
    <meta name="description" content="1、什么是进程、线程？
进程：进程是系统分配资源的最小单位，电脑中运行的一个程序就是一个进程，比如QQ打开后，就会有一个进程
线程：线程是比进程更小的单位，是CPU调度的最小的单位，在一个进程中可以划分多个进程，这些进程，共享进程的堆区和方">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Java多线程面试题 | 生如夏花</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">生如夏花</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>主页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="Search"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">生如夏花</div>
        <div class="logo-desc">
            
            从来没有真正的绝境，只有心灵的迷途
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                主页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/jackliu7" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/jackliu7" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Java多线程面试题
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/java/" target="_blank">
                                <span class="chip bg-color">java</span>
                            </a>
                        
                            <a href="/tags/多线程/" target="_blank">
                                <span class="chip bg-color">多线程</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/java/" class="post-category" target="_blank">
                                java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2019-06-04
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>Word Count:&nbsp;&nbsp;
                        4.9k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>Read Times:&nbsp;&nbsp;
                        17 Min
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>Read Count:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="1、什么是进程、线程？"><a href="#1、什么是进程、线程？" class="headerlink" title="1、什么是进程、线程？"></a>1、什么是进程、线程？</h2><ul>
<li>进程：进程是系统分配资源的最小单位，电脑中运行的一个程序就是一个进程，比如QQ打开后，就会有一个进程</li>
<li>线程：线程是比进程更小的单位，是CPU调度的最小的单位，在一个进程中可以划分多个进程，这些进程，共享进程的堆区和方法区的共享资源，但他们都有各自的虚拟机栈，程序计数器，本地方法栈，这些线程之间的切换比进程之间的切换快很多，所以线程也叫轻量级的进程。<a id="more"></a>
<h2 id="2、什么是线程安全和线程不安全？"><a href="#2、什么是线程安全和线程不安全？" class="headerlink" title="2、什么是线程安全和线程不安全？"></a>2、什么是线程安全和线程不安全？</h2></li>
<li>当有多个线程同时访问一个共享资源时就会出现线程安全的问题，如果同一时间只有一个线程能得到共享资源就是线程安全的，也就是其他的线程的执行不会让当前线程产生错误，比如有一个共享变量a初始值为0，有1000个线程对a进行加一操作，如果不加保护的话，结果可能会小于1000，这就是线程不安全的。</li>
</ul>
<h2 id="3、什么是自旋锁？"><a href="#3、什么是自旋锁？" class="headerlink" title="3、什么是自旋锁？"></a>3、什么是自旋锁？</h2><ul>
<li>当多个线程访问临界区是，线程这有拿到了监视器锁之后才能执行临界区的代码，但同一时间只有一个线程拿到锁，没到到锁的线程只有变为阻塞状态，自旋锁认为线程等待的时间是非常短的，所以没拿到所得时候，就执行一个循环等待，直到拿到锁，这样线程就不会进入阻塞状态，但自旋的缺点就是，在自选的过程中会消耗CPU资源，造成浪费，也有自适应的自旋锁，可以根据不同的情况来调整自旋的时间。</li>
</ul>
<h2 id="4、什么是Java内存模型？"><a href="#4、什么是Java内存模型？" class="headerlink" title="4、什么是Java内存模型？"></a>4、什么是Java内存模型？</h2><ul>
<li>Java内存模型试图屏蔽不同硬件不同操作系统内存访问的差异，以实现java在不同平台访问内存都达到同样的效果</li>
<li>CPU处理的速度和内存的速度是相差很大的，这样CPU就会受到内存速度的限制导致CPU利用率不高，为了解决这个问题就在CPU中加入了缓存，所以每个线程不仅有共享的主存还有自己的缓存，缓存中存放的是主存的副本，CPU操作的是cache中的副本，在适当的时间把cache中的数据写会主存。</li>
</ul>
<h2 id="5、什么是CAS？"><a href="#5、什么是CAS？" class="headerlink" title="5、什么是CAS？"></a>5、什么是CAS？</h2><ul>
<li><strong>CAS是指compare and swap，意识是指一个旧的预期值A,主内存的值是B，要修改的值C，当且仅当A==B的时候，A的值才会被修改成C，而且这个操作是原子性的，是一个非阻塞性的 乐观锁</strong>，比如在主存中有一个变量a = 1,线程的工作内存中有一个变量a的副本，现在线程要把a变成2，CAS就会用native本地方法比较工作内存中的值和主存中的值是否相等，如果相等则更新，防止了其他线程对数据的修改，当前线程修改了a后，其他线程工作内存中的缓存就会失效，会从新从主存中获取。</li>
</ul>
<h2 id="6、什么是乐观锁和悲观锁？"><a href="#6、什么是乐观锁和悲观锁？" class="headerlink" title="6、什么是乐观锁和悲观锁？"></a>6、什么是乐观锁和悲观锁？</h2><ul>
<li>乐观锁：对数据持一种乐观的态度，认为在并发过程中不会有别的线程修改当前线程用的数据，等到了真的用到数据的时候在检查数据有没有被别的线程修改过，比如CAS就是乐观锁</li>
<li>悲观锁：对数据持一种悲观的态度，认为别的线程会修改当前线程用的数据，所以线程会加锁，用完了在解锁，比如容synchronize</li>
</ul>
<p>7、什么是AQS？</p>
<h2 id="8、什么是原子操作？在Java-Concurrency-API中有哪些原子类-atomic-classes-？"><a href="#8、什么是原子操作？在Java-Concurrency-API中有哪些原子类-atomic-classes-？" class="headerlink" title="8、什么是原子操作？在Java Concurrency API中有哪些原子类(atomic classes)？"></a>8、什么是原子操作？在Java Concurrency API中有哪些原子类(atomic classes)？</h2><ul>
<li>原子在化学中是不可再分的，一个原子操作通常包含几个操作，这几个操作都成功了这个原子操作才算成功，如果有一个失败了，其他的操作也会失败。</li>
</ul>
<p><font color="red">❤</font>1.基本类型</p>
<ul>
<li>AtomicInteger：整形原子类</li>
<li>AtomicLong：长整型原子类</li>
<li>AtomicBoolean：布尔型原子类</li>
</ul>
<p><font color="red">❤</font>2.数组类型</p>
<ul>
<li>AtomicIntegerArray：整形数组原子类 </li>
<li>AtomicLongArray：长整形数组原子类</li>
<li>AtomicReferenceArray：引用类型数组原子类</li>
</ul>
<p><font color="red">❤</font>3.引用类型</p>
<ul>
<li>AtomicReference：引用类型原子类 </li>
<li>AtomicStampedRerence：原子更新引用类型里的字段原子</li>
<li>AtomicMarkableReference ：原子更新带有标记位的引用类型</li>
</ul>
<p><font color="red">❤</font>4.对象的属性修改类型</p>
<ul>
<li>AtomicIntegerFieldUpdater：原子更新整形字段的更新器</li>
<li>AtomicLongFieldUpdater：原子更新长整形字段的更新器<ul>
<li>AtomicStampedReference：原子更新带有版本号的引用类型。该类将整数值与引用关联起来，可用于解决原子的更新数据和数据的版本号，可以解决使用CAS 进行原子更新时可能出现的 ABA 问题。</li>
</ul>
</li>
</ul>
<p>9、什么是Executors框架？</p>
<h2 id="10、什么是阻塞队列？如何使用阻塞队列来实现生产者-消费者模型？"><a href="#10、什么是阻塞队列？如何使用阻塞队列来实现生产者-消费者模型？" class="headerlink" title="10、什么是阻塞队列？如何使用阻塞队列来实现生产者-消费者模型？"></a>10、什么是阻塞队列？如何使用阻塞队列来实现生产者-消费者模型？</h2><p> &nbsp; &nbsp;BlockingQueue有两种实现方式</p>
<ol>
<li>FIFO队列：LinkBlockingQueue,ArrayBlockingQueue（固定长度）</li>
<li><p>优先级队列：PriorityBlockingQueue</p>
<blockquote>
<p><font size="3" color="green">BlockingQueue提供了take()和put()方法，当队列中是空的时候，take会阻塞知道队列中有东西，当队列满了以后，put()方法会阻塞，等到队列有位置后才可以入队</font></p>
</blockquote>
<p>&nbsp; &nbsp;BlockingQueue 实现生产者消费者问题</p>
</li>
</ol>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ProducerConsumer</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> BlockingQueue<span class="token operator">&lt;</span>String<span class="token operator">></span> queue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayBlockingQueue</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">Producer</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                queue<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"product"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"produce.."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">Consumer</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                String product <span class="token operator">=</span> queue<span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span><span class="token string">"consume.."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">2</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        Producer producer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Producer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        producer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">5</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        Consumer consumer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Consumer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        consumer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">3</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        Producer producer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Producer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        producer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre>
<pre class=" language-log"><code class="language-log">produce..produce..consume..consume..produce..consume..produce..consume..produce..consume..

</code></pre>
<h2 id="11、什么是Callable和Future"><a href="#11、什么是Callable和Future" class="headerlink" title="11、什么是Callable和Future?"></a>11、什么是Callable和Future?</h2><ul>
<li>在jdk1.5之前，如果需要获取子线程执行结果，就必须通过共享变量或者使用线程通信的方式来达到效果，这样使用起来就比较麻烦，在1.5之后提供了Callable和Future接口，用他们可以方便的获得线程的返回值，首先创建一个实现了Callable接口的类，然后创建一个FutureTask，把Callable当做参数，然后创建一个Thread来驱动FutureTask，可以用FutureTask的get方法获取返回值</li>
</ul>
<h2 id="12、什么是FutureTask"><a href="#12、什么是FutureTask" class="headerlink" title="12、什么是FutureTask?"></a>12、什么是FutureTask?</h2><ul>
<li>FutureTask实现了RunableFuture接口，RunableFuture接口有继承了Future可Runable接口，通过FutureTask可以获得Callable的返回值</li>
</ul>
<h2 id="13、什么是同步容器和并发容器的实现？"><a href="#13、什么是同步容器和并发容器的实现？" class="headerlink" title="13、什么是同步容器和并发容器的实现？"></a>13、什么是同步容器和并发容器的实现？</h2><ul>
<li>同步容器：同步容器可以简单的理解为加了synchronize锁的容器，比如Vector，Hashtable，以及Collections.synchronizedSet，synchronizedList等方法返回的容器。这些容器为了线程安全都加了synchronize锁，但这些容器几乎没有用，因为在并发中效率太低了</li>
<li>并发容器：并发容器采用了一种颗粒更细的加锁方式，可以称为分段加锁，比如ConcurrentHashMap，在这种锁机制下，允许任意数量的读线程并发地访问map，并且执行读操作的线程和写操作的线程也可以并发的访问map，同时允许一定数量的写操作线程并发地修改map，所以它可以在并发环境下实现更高的吞吐量。<h2 id="14、什么是多线程？优缺点？"><a href="#14、什么是多线程？优缺点？" class="headerlink" title="14、什么是多线程？优缺点？"></a>14、什么是多线程？优缺点？</h2></li>
</ul>
<blockquote>
<p><font size="3" color="green">多线程就是多个线程并发执行，一个进程要完成一个任务，把这个任务划分成更小的任务分给每一个线程，这几个线程并发执行，就是多线程</font></p>
</blockquote>
<p><font color="red">❤</font>优点：</p>
<ol>
<li>从计算机底层来说：线程可以看作是轻量级的进程，是CPU调度的最小的单位，线程之间的切换要比进程之间切换快的多，另外，多核 CPU 时代意味着多个线程可以同时运行，这减少了线程上下文切换的开销。</li>
<li>从当代的互联网来说：现在的系统动不动就要求千万级的并发，而多线程并发编程是并发系统的基础，利用好多线程可以大大提高系统的并发量</li>
<li>可以提高CPU的利用率：在单核时代，要先进行IO然后再进行计算，这样二者的利用率只有50%，多线程可以在CPU计算的时候进行IO操作这样CPU的利用率就提高了，在多核时代，假如有一个任务，把这个任务分配给不同的线程，这些线程在不同的CPU中跑，可以让每一个CPU充分利用。</li>
</ol>
<p><font color="red">❤</font>缺点：</p>
<ul>
<li>并发编程的目的是提高程序的执行效率提高程序执行的速度，但也存在很多问题比如上下文之间的切换问题，死锁问题，以及受限于软件和硬件资源的问题。</li>
</ul>
<h2 id="15、什么是多线程的上下文切换？"><a href="#15、什么是多线程的上下文切换？" class="headerlink" title="15、什么是多线程的上下文切换？"></a>15、什么是多线程的上下文切换？</h2><ul>
<li>并发执行的每个线程都会分一个时间片，当线程的执行时间到了，就会让出CPU给别的线程执行，线程保存当前执行的状态，到下一个线程执行的过程就是上下文切换。上下文切换是非常频繁的，一秒钟要切换上百次，每一次切换都是纳秒级别的，所以上下文切换是非常消耗CPU的，有可能是操作系统消耗最大的操作，linux比其他系统有很多优点，其中一个就是上下文切换的速度很快。</li>
</ul>
<h2 id="16、ThreadLocal的设计理念与作用？"><a href="#16、ThreadLocal的设计理念与作用？" class="headerlink" title="16、ThreadLocal的设计理念与作用？"></a>16、ThreadLocal的设计理念与作用？</h2><blockquote>
<p><font size="3" color="green">在并发编程中每一个线程都可以使用共享资源，所以我们要对这些共享资源做同步，但做同步会涉及到很多问题，所以为什么不让每个线程都拥有这个共享资源的副本呢，那每个线程对副本进行修改，就互不干扰了，所以ThreadLocal就是解决这个问题的，ThreadLocal可以绑定每个线程的数据，当线程访问该变量的时候就会拿到当前线程的变量。</font></p>
</blockquote>
<ul>
<li><font color="red">❤</font>原理：在ThreadLocal类中有一个Map，Map以线程为Key值，所以线程可以拿到当前线程绑定的数据。</li>
</ul>
<ul>
<li><font color="red">❤</font>存在的问题：Map中的key值是threadlocald的弱引用，当没有被外部强引用的时候会被清理，但value是强引用不会被清理，所以就存在Key为null的值，这样就会造成内存泄漏，但ThreadLocalMap已经解决了这个问题，在每次get()和set()的时候都会清理key为null的值</li>
<li><font color="red">❤</font>应用举例：在数据库额连接池中要保证每个线程都拥有自己的connection，不然事务就会出现混乱，所以就可以把每个线程的connection绑定到当前前程中去，就可以保证同一个线程用同一个连接</li>
</ul>
<h2 id="17、ThreadPool（线程池）用法与优势？"><a href="#17、ThreadPool（线程池）用法与优势？" class="headerlink" title="17、ThreadPool（线程池）用法与优势？"></a>17、ThreadPool（线程池）用法与优势？</h2><ol>
<li>降低资源消耗。 通过重复利用已创建的线程降低线程创建和销毁造成的消耗。</li>
<li>提高响应速度。 当任务到达时，任务可以不需要的等到线程创建就能立即执行。</li>
<li>提高线程的可管理性。线程是稀缺资源，如果无限制的创建，不仅会消耗系统资源，还会降低系统的稳定性，使用线程池可以进行统一的分配，调优和监控。</li>
</ol>
<h2 id="18、Concurrent包里的其他东西"><a href="#18、Concurrent包里的其他东西" class="headerlink" title="18、Concurrent包里的其他东西"></a>18、Concurrent包里的其他东西</h2><ul>
<li>ArrayBlockingQueue、CountDownLatch等等。</li>
</ul>
<h2 id="19、synchronized和ReentrantLock的区别？"><a href="#19、synchronized和ReentrantLock的区别？" class="headerlink" title="19、synchronized和ReentrantLock的区别？"></a>19、synchronized和ReentrantLock的区别？</h2><ol>
<li>都是可重入锁</li>
<li>synchronized是基于jvm层面的ReentrantLock是基于jdk层面的</li>
<li>ReentrantLock比synchronized的功能更多：①等待可中断；②可实现公平锁；③可实现选择性通知（锁可以绑定多个条件）</li>
</ol>
<h2 id="20、Semaphore有什么作用？"><a href="#20、Semaphore有什么作用？" class="headerlink" title="20、Semaphore有什么作用？"></a>20、Semaphore有什么作用？</h2><blockquote>
<p><font size="3" color="green">Semaphore 类似于操作系统中的信号量，可以控制对互斥资源的访问线程数。</font></p>
</blockquote>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SemaphoreExample</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">final</span> <span class="token keyword">int</span> clientCount <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token keyword">int</span> totalRequestCount <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
        Semaphore semaphore <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Semaphore</span><span class="token punctuation">(</span>clientCount<span class="token punctuation">)</span><span class="token punctuation">;</span>
        ExecutorService executorService <span class="token operator">=</span> Executors<span class="token punctuation">.</span><span class="token function">newCachedThreadPool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> totalRequestCount<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            executorService<span class="token punctuation">.</span><span class="token function">execute</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">-</span><span class="token operator">></span><span class="token punctuation">{</span>
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    semaphore<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span>semaphore<span class="token punctuation">.</span><span class="token function">availablePermits</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
                    semaphore<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        executorService<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<pre class=" language-html"><code class="language-html">before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..after..

</code></pre>
<h2 id="21、Java-Concurrency-API中的Lock接口-Lock-interface-是什么？对比同步它有什么优势？"><a href="#21、Java-Concurrency-API中的Lock接口-Lock-interface-是什么？对比同步它有什么优势？" class="headerlink" title="21、Java Concurrency API中的Lock接口(Lock interface)是什么？对比同步它有什么优势？"></a>21、Java Concurrency API中的Lock接口(Lock interface)是什么？对比同步它有什么优势？</h2><p>Lock接口比同步方法和同步块提供了更具扩展性的锁操作。<br>他们允许更灵活的结构，可以具有完全不同的性质，并且可以支持多个相关类的条件对象。<br>它的优势有</p>
<ol>
<li>可以使锁更公平</li>
<li>可以使线程在等待锁的时候响应中断</li>
<li>可以让线程尝试获取锁，并在无法获取锁的时候立即返回或者等待一段时间 可以在不同的范围，以不同的顺序获取和释放锁</li>
</ol>
<p>整体上来说Lock是synchronized的扩展版，Lock提供了无条件的、可轮询的(tryLock方法)、定时的(tryLock带参方法)、可中断的(lockInterruptibly)、可多条件队列的(newCondition方法)锁操作。另外Lock的实现类基本都支持非公平锁(默认)和公平锁，synchronized只支持非公平锁，当然，在大部分情况下，非公平锁是高效的选择。</p>
<p>22、Hashtable的size()方法中明明只有一条语句”return count”，为什么还要做同步？</p>
<p>23、ConcurrentHashMap的并发度是什么？</p>
<p>24、ReentrantReadWriteLock读写锁的使用？</p>
<p>25、CyclicBarrier和CountDownLatch的用法及区别？</p>
<p>26、LockSupport工具？</p>
<p>27、Condition接口及其实现原理？</p>
<p>28、Fork/Join框架的理解?</p>
<h2 id="29、wait-和sleep-的区别"><a href="#29、wait-和sleep-的区别" class="headerlink" title="29、wait()和sleep()的区别?"></a>29、wait()和sleep()的区别?</h2><ul>
<li>wait()和sleep()都可以暂定现在的进程，但是wait()会释放当前的锁，但sleep不会释放锁，sleep在时间到了以后会自己苏醒，继续执行，而wait需要别的线程调用他的notify()或者notifyAll()方法。</li>
</ul>
<h2 id="30、线程的五个状态（五种状态，创建、就绪、运行、阻塞和死亡）"><a href="#30、线程的五个状态（五种状态，创建、就绪、运行、阻塞和死亡）" class="headerlink" title="30、线程的五个状态（五种状态，创建、就绪、运行、阻塞和死亡）?"></a>30、线程的五个状态（五种状态，创建、就绪、运行、阻塞和死亡）?</h2><p><img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/adfb427d-3b21-40d7-a142-757f4ed73079.png" alt="在这里插入图片描述"></p>
<ul>
<li>当线程创建完成以后就是New（新建）状态，当调用star()之后就成为Runnable可运行状态，可运行状态其实包含就绪状态和运行状态，当线程得到时间片后就成为运状态，当线程没有获得排它锁的时候就会变成阻塞状态，调用了wait()，方法后就会成为waiting状态。</li>
</ul>
<h2 id="31、start-方法和run-方法的区别？"><a href="#31、start-方法和run-方法的区别？" class="headerlink" title="31、start()方法和run()方法的区别？"></a>31、start()方法和run()方法的区别？</h2><blockquote>
<p><font size="3" color="green">当创建了一个线程后，线程就会进入新建状态，当调用star()后就会进入就绪状态，一旦获得时间片后就会进入运行状态，会自动的执行线程中的run()方法，调用start（）方法会启动一个线程，和当前线程是异步的，而调用run()方法只是调用了线程中的一个普通方法，和调用普通类的方法没什么区别，没有启动线程，和当前的线程是同步执行的。</font></p>
</blockquote>
<h2 id="32、Runnable接口和Callable接口的区别？"><a href="#32、Runnable接口和Callable接口的区别？" class="headerlink" title="32、Runnable接口和Callable接口的区别？"></a>32、Runnable接口和Callable接口的区别？</h2><blockquote>
<p><font size="3" color="green">实现了Runnable和Callable接口的类只是一个任务，并不能算是一个线程，需要通过Thread来调用，可以说任务是通过线程驱动而执行的。二者的区别就是Callable接口可以有返回值，返回值通过 FutureTask 进行封装。</font></p>
</blockquote>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyCallable</span> <span class="token keyword">implements</span> <span class="token class-name">Callable</span><span class="token operator">&lt;</span>Integer<span class="token operator">></span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> Integer <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> ExecutionException<span class="token punctuation">,</span> InterruptedException <span class="token punctuation">{</span>
    MyCallable mc <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyCallable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    FutureTask<span class="token operator">&lt;</span>Integer<span class="token operator">></span> ft <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FutureTask</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span>mc<span class="token punctuation">)</span><span class="token punctuation">;</span>
    Thread thread <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>ft<span class="token punctuation">)</span><span class="token punctuation">;</span>
    thread<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>ft<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
<h2 id="33、volatile关键字的作用？"><a href="#33、volatile关键字的作用？" class="headerlink" title="33、volatile关键字的作用？"></a>33、volatile关键字的作用？</h2><blockquote>
<p><font size="3" color="green">volatile关键字可以实现多线程之间数据的可见性，但并不能保证在多线程下是线程安全的，而且可以防止指令重排</font></p>
</blockquote>
<p><font color="red">❤</font>原理：</p>
<ul>
<li>由于CPU和内存之间速度相差很大，这样会导致CPU的利用率不高，所以在CPU中加了缓存，这样就可以解决这个问题，java内存模型中每次不是从主存中取数据，而是从每个线程自己的工作内存中取数据，但是这样就会造成一个问题就是在多线程中会出现缓存不一致的问题，比如有一个变量a在主存中的初始值是1，每个线程的工作内存中都有一个a的副本，当一个线程修改了a的值，这时候a变成了0，但是其他线程并不知道，其他线程自己的工作内存中还是原来的旧值，当加了volatile关键字后，就要遵循操作系统的缓存一致协议，当前线程修改了之后，会被强制刷回主存，每一个线程就会在总线上嗅探是否有值改变了，如果发现主存中的值变了，那工作内存中的值就会失效，也就是，当前线程对值的修改对其他线程是可见的。</li>
<li>虽然可以实现数据的可见性，但并不能保证原子性，所以在多线程下并不能保证是线程安全的</li>
</ul>
<p>34、Java中如何获取到线程dump文件？</p>
<h2 id="35、线程和进程有什么区别？"><a href="#35、线程和进程有什么区别？" class="headerlink" title="35、线程和进程有什么区别？"></a>35、线程和进程有什么区别？</h2><ol>
<li>线程是资源分配的最小单位，进程是CPU调度的最小单位</li>
<li>线程之间的切换比进程之间的切换快很多，线程可以看成是轻量级的进程</li>
<li>进程之间是独立的，线程之间是相互联系的，线程之间共享进程的共享资源</li>
</ol>
<h2 id="36、线程实现的方式有几种（四种）？"><a href="#36、线程实现的方式有几种（四种）？" class="headerlink" title="36、线程实现的方式有几种（四种）？"></a>36、线程实现的方式有几种（四种）？</h2><ol>
<li>继承Thread类</li>
<li>实现Runnable接口</li>
<li>实现Callable接口</li>
<li>4.使用线程池（有返回值</li>
</ol>
<p>37、高并发、任务执行时间短的业务怎样使用线程池？并发不高、任务执行时间长的业务怎样使用线程池？并发高、业务执行时间长的业务怎样使用线程池？</p>
<p>38、如果你提交任务时，线程池队列已满，这时会发生什么？</p>
<p>39、锁的等级：方法锁、对象锁、类锁?</p>
<p>40、如果同步块内的线程抛出异常会发生什么？</p>
<p>41、并发编程（concurrency）并行编程（parallellism）有什么区别？</p>
<h2 id="42、如何保证多线程下-i-结果正确？"><a href="#42、如何保证多线程下-i-结果正确？" class="headerlink" title="42、如何保证多线程下 i++ 结果正确？"></a>42、如何保证多线程下 i++ 结果正确？</h2><p> <font color="red">❤</font>1. 可以用synchronize关键字</p>
<p><font color="red">❤</font> 2. 用CAS+volatile</p>
<p>43、一个线程如果出现了运行时异常会怎么样?</p>
<p>44、如何在两个线程之间共享数据?</p>
<p>45、生产者消费者模型的作用是什么?</p>
<p>46、怎么唤醒一个阻塞的线程?</p>
<p>47、Java中用到的线程调度算法是什么</p>
<h2 id="48、单例模式的线程安全性"><a href="#48、单例模式的线程安全性" class="headerlink" title="48、单例模式的线程安全性?"></a>48、单例模式的线程安全性?</h2><pre class=" language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Singleton</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">volatile</span> <span class="token keyword">static</span> Singleton uniqueInstance<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token function">Singleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> Singleton <span class="token function">getUniqueInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
       <span class="token comment" spellcheck="true">//先判断对象是否已经实例过，没有实例化过才进入加锁代码</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>uniqueInstance <span class="token operator">==</span> null<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">//类对象加锁</span>
            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>Singleton<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>uniqueInstance <span class="token operator">==</span> null<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    uniqueInstance <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Singleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> uniqueInstance<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p>49、线程类的构造方法、静态块是被哪个线程调用的?</p>
<h2 id="50、同步方法和同步块，哪个是更好的选择"><a href="#50、同步方法和同步块，哪个是更好的选择" class="headerlink" title="50、同步方法和同步块，哪个是更好的选择?"></a>50、同步方法和同步块，哪个是更好的选择?</h2><ul>
<li>应该尽量使用同步块而不是同步方法，这样可以缩小同步范围，从而减少锁争用</li>
</ul>
<h2 id="51、如何检测死锁？怎么预防死锁？"><a href="#51、如何检测死锁？怎么预防死锁？" class="headerlink" title="51、如何检测死锁？怎么预防死锁？"></a>51、如何检测死锁？怎么预防死锁？</h2><p>&nbsp;&nbsp;死锁满足的条件</p>
<ol>
<li>互斥资源</li>
<li>不可剥夺</li>
<li>请求保持</li>
<li>环路等待</li>
</ol>

            </div>
            <hr>

            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            


        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/Java7和8+中的+HashMap+和+ConcurrentHashMap+全解析.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/7.jpg" class="responsive-img" alt="Java7/8 中的 HashMap 和 ConcurrentHashMap 全解析">
                        
                        <span class="card-title">Java7/8 中的 HashMap 和 ConcurrentHashMap 全解析</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            网上关于 HashMap 和 ConcurrentHashMap 的文章确实不少，不过缺斤少两的文章比较多，所以才想自己也写一篇，把细节说清楚说透，尤其像 Java8 中的 ConcurrentHashMap，大部分文章都说不清楚。终归是希
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-06-07
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/java/" class="post-category" target="_blank">
                                    java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/HashMap/" target="_blank">
                        <span class="chip bg-color">HashMap</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/vim编辑器常用的操作.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="vim编辑器常用的操作">
                        
                        <span class="card-title">vim编辑器常用的操作</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
Linux的命令行界面下面有非常多的文本编辑器。比如经常听说的就有Emacs、pico、nano、joe与vim等。vim也是许多linux自带的编辑器，想要玩好linux，vim一定是要熟练使用的，利用好vim会让我们事半功倍

vi的
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-05-24
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/linux/" class="post-category" target="_blank">
                                    linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/linux/" target="_blank">
                        <span class="chip bg-color">linux</span>
                    </a>
                    
                    <a href="/tags/vim/" target="_blank">
                        <span class="chip bg-color">vim</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackliu7" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:liudazh@outlook.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2263132654" class="tooltipped" data-tooltip="QQ联系我: 2263132654" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>


</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>